# -*- coding: utf-8 -*-
import csv
from django import forms
from django.http import HttpResponse

from google.appengine.ext.db import djangoforms
from google.appengine.ext import db

from base.views import get_objects_page_context
from base.models import School, SCHOOL_TYPE, SchoolManager, ClassProperty, OneClass
from base.util.decorators import render_to, login_required, admin_required
from base.util.emc import _kr

import logging

@login_required
@render_to('school/list.html')
def list(request):
    query = School.gql('ORDER BY name ASC')
    schools = query.fetch(1000)
    stat = {}
    for t in SCHOOL_TYPE:
        stat[t] = sum([1 for s in schools if s.stage == t])
    stat['M'] += stat['GM']
    stat['H'] += stat['GH']
    stat['etc'] += stat['U']
    return {
            'schools': schools,
            'stat': stat
            }


@login_required
def list_csv(request):
    query = School.gql('order by name ASC')
    schools = query.fetch(1000)

    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=school.csv'

    writer = csv.writer(response)
    for school in schools:
        writer.writerow([
                         school.year,
                         _kr(school.name),
                         school.en_name,
                         school.stage,
                         _kr(school.province),
                         _kr(school.local),
                         school.phone,
                         _kr(school.address),
                         school.postcode,
                         school.IPs,
                         school.coordinator,
                         _kr(school.principal),
                         _kr(school.vice_principal),
                         _kr(school.log),
                        ])
    return response

class SchoolForm(djangoforms.ModelForm):
    class Meta:
        model = School
        exclude = ('id',)

    def clean(self):
        cleaned_data = self.cleaned_data
        year = cleaned_data.get('year')
        name = cleaned_data.get('name','')
        en_name = cleaned_data.get('en_name','')
        stage = cleaned_data.get('stage')
        local = cleaned_data.get('local')
        if not name:
            raise forms.ValidationError(u'학교 이름은 필수입니다.')
        if not en_name:
            raise forms.ValidationError(u'영문학교 이름은 필수입니다.')
        if not local:
            raise forms.ValidationError(u'지역 이름은 필수입니다.')

        school = SchoolManager.is_exist(year, name, stage, local)
        if not self.instance and school:
            raise forms.ValidationError(u'같은 school이 이미 존재합니다.')
        if self.instance:
            if (self.instance.name != name or
                self.instance.year != year or
                self.instance.stage != stage or
                self.instance.local != local) and\
                school:
                raise forms.ValidationError(u'같은 school이 이미 존재합니다.')
        return cleaned_data

@admin_required
@render_to('school/form.html')
def create(request):
    form = SchoolForm()
    if request.method == 'POST':
        form = SchoolForm(request.POST)
        if form.is_valid():
            school = form.save(commit=False)
            school.put()
            return school.get_absolute_url
    return {'form': form}

@admin_required
@render_to('school/detail.html')
def detail(request, school_id):
    school = School.get_using_id(int(school_id))
    query = ClassProperty.gql('WHERE school=:1 order by grade ASC', school.key())
    classproperties = query.fetch(1000)
#    query = db.GqlQuery("SELECT * FROM OneClass WHERE ANCESTOR IS :parent order by date", parent=school.key())
    query = db.GqlQuery("SELECT * FROM OneClass WHERE school=:school ORDER BY date", school=school.key())
    oneclasses = query.fetch(1000)
    return {
        'school': school,
        'classproperties': classproperties,
        'oneclasses': oneclasses,
        }

@admin_required
@render_to('school/form.html')
def change(request, school_id):
    school = School.get_using_id(int(school_id))
    form = SchoolForm(request.POST or None, instance=school)
    if form.is_valid():
        school = form.save()
        return school.get_absolute_url
    return {'form': form}

#@render_to('school/form.html')
#def delete(request, school_id):
#    school = School.get_using_id(int(school_id))
#    form = SchoolForm(request.POST or None, instance=school)
#    if form.is_valid():
#        school = form.save()
#        return school.get_absolute_url
#    return {'form': form}



